// 初始化博客数据
function loadBlogsFromStorage() {
    const storedBlogs = localStorage.getItem('blogs');
    return storedBlogs ? JSON.parse(storedBlogs) : [
        {
            id: 1,
            title: "第一篇博客",
            content: "这是我的第一篇博客内容。",
            author: "admin"
        }
    ];
}

let blogs = loadBlogsFromStorage();

// 登录功能
document.getElementById('login-form').addEventListener('submit', (e) => {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    // 简单验证用户名和密码
    if (username === 'admin' && password === '123456') {
        alert('登录成功！');
        localStorage.setItem('isLoggedIn', 'true'); // 模拟登录状态
        showBlogSection(); // 跳转到博客页面
    } else {
        document.getElementById('login-error').textContent = '用户名或密码错误';
    }
});

function showBlogSection() {
    document.getElementById('login-section').style.display = 'none';
    document.getElementById('blog-section').style.display = 'block';
    loadBlogs(); // 加载博客列表
}

// 发布博客功能
document.getElementById('upload-blog-form').addEventListener('submit', (e) => {
    e.preventDefault();
    const isLoggedIn = localStorage.getItem('isLoggedIn');
    if (!isLoggedIn) {
        alert('请先登录！');
        return;
    }

    const title = document.getElementById('title').value;
    const content = document.getElementById('content').value;

    // 添加新博客
    const newBlog = {
        id: blogs.length + 1,
        title,
        content,
        author: 'admin',
    };
    blogs.push(newBlog);

    // 更新localStorage
    localStorage.setItem('blogs', JSON.stringify(blogs));

    // 清空表单并刷新博客列表
    document.getElementById('upload-blog-form').reset();
    loadBlogs();
    alert('博客发布成功！');
});

// 展示博客功能
function loadBlogs() {
    const isLoggedIn = localStorage.getItem('isLoggedIn');
    if (!isLoggedIn) {
        alert('请先登录！');
        return;
    }

    const blogList = document.getElementById('blogs');
    blogList.innerHTML = ''; // 清空旧列表

    // 动态生成博客列表
    blogs.forEach((blog) => {
        const li = document.createElement('li');
        li.innerHTML = `
      <strong>${blog.title}</strong><br>
      ${blog.content}<br>
      <small>作者: ${blog.author}</small>
    `;
        blogList.appendChild(li);
    });
}

// 页面加载时自动加载博客
window.onload = () => {
    const isLoggedIn = localStorage.getItem('isLoggedIn');
    if (isLoggedIn) {
        showBlogSection();
    }
};